package com.study.talk.common.util;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MyFileUtils {
    public static String getFileSuffix(String name){
        int index = name.lastIndexOf(".");
        return name.substring(index);
    }

    /**
     * 调用此方法即可实现断点下载
     *
     */
    public static void downloadFile(File file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!file.exists()) {
            response.sendError(404);
            return;
        }
        String range = request.getHeader("Range");
        long start = 0;
        long end = file.length() - 1;
        if (!StringUtils.isEmpty(range)) {
            String[] arr = range.substring("bytes=".length()).split("-");
            if (arr.length > 0) {
                start = Long.valueOf(arr[0]);
                if (arr.length > 1) {
                    end = Long.valueOf(arr[1]);
                }
            }
            response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + file.length());
            response.setStatus(206);
        }

        long contentLength = end - start + 1;
        String fileName = new String(file.getName().getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        response.addHeader("Content-Length", String.valueOf(contentLength));
        response.setContentType(Files.probeContentType(Paths.get(file.getAbsolutePath())));
        response.setHeader("Last-Modified", String.valueOf(file.lastModified()));
        response.setHeader("Accept-Ranges", "bytes");
        response.setBufferSize(2048);

        FileInputStream in = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        try {
            StreamUtils.copyRange(in, out, start, end);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

}
